package com.fl.nj.controller;

import com.fl.nj.entity.Menu;
import com.fl.nj.exception.ApiResponse;
import com.fl.nj.exception.BusinessException;
import com.fl.nj.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;

import java.util.List;
import java.util.NoSuchElementException;

/**
 * 菜单Controller
 */
@RestController
@RequestMapping("/api/menu")
@CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS})
public class MenuController {

    @Autowired
    private MenuService menuService;

    /**
     * 获取所有菜单
     * 
     * @return 菜单列表
     */
    @GetMapping
    public ApiResponse<List<Menu>> findAll(HttpServletResponse response) {
        // 设置响应头，确保中文正确显示
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        
        List<Menu> menuList = menuService.findAll();
        return ApiResponse.success(menuList);
    }

    /**
     * 根据ID获取菜单
     * 
     * @param id 菜单ID
     * @return 菜单对象
     */
    @GetMapping("/{id}")
    public ApiResponse<Menu> findById(@PathVariable Long id) {
        Menu menu = menuService.findById(id);
        if (menu == null) {
            throw new NoSuchElementException("菜单不存在");
        }
        return ApiResponse.success(menu);
    }

    /**
     * 根据父菜单ID获取子菜单
     * 
     * @param parentId 父菜单ID
     * @return 子菜单列表
     */
    @GetMapping("/parent/{parentId}")
    public ApiResponse<List<Menu>> findByParentId(@PathVariable Long parentId) {
        List<Menu> menuList = menuService.findByParentId(parentId);
        return ApiResponse.success(menuList);
    }

    /**
     * 获取菜单树结构
     * 
     * @return 菜单树列表
     */
    @GetMapping("/tree")
    public ApiResponse<List<Menu>> findMenuTree() {
        List<Menu> menuTree = menuService.findMenuTree();
        return ApiResponse.success(menuTree);
    }

    /**
     * 添加菜单
     * 
     * @param menu 菜单对象
     * @return 操作结果
     */
    @PostMapping
    public ApiResponse<Menu> insert(@RequestBody Menu menu) {
        // 参数验证
        if (menu.getMenuName() == null || menu.getMenuName().trim().isEmpty()) {
            throw new BusinessException(400, "菜单名称不能为空");
        }

        // 验证父菜单是否存在（如果不是顶级菜单）
        if (menu.getParentId() != null && menu.getParentId() != 0) {
            Menu parentMenu = menuService.findById(menu.getParentId());
            if (parentMenu == null) {
                throw new BusinessException(400, "父菜单不存在");
            }
        }

        int count = menuService.insert(menu);
        if (count <= 0) {
            throw new BusinessException(500, "添加失败");
        }

        // 获取插入后的菜单信息（包含自增ID）
        Menu insertedMenu = menuService.findById(menu.getId());
        return ApiResponse.success(insertedMenu);
    }

    /**
     * 更新菜单
     * 
     * @param id   菜单ID
     * @param menu 菜单对象
     * @return 操作结果
     */
    @PutMapping("/{id}")
    public ApiResponse<Menu> update(@PathVariable Long id, @RequestBody Menu menu) {
        // 验证ID是否匹配
        if (menu.getId() != null && !menu.getId().equals(id)) {
            throw new BusinessException(400, "请求路径中的ID与请求体中的ID不匹配");
        }

        // 检查菜单是否存在
        Menu existingMenu = menuService.findById(id);
        if (existingMenu == null) {
            throw new NoSuchElementException("菜单不存在");
        }

        // 参数验证
        if (menu.getMenuName() == null || menu.getMenuName().trim().isEmpty()) {
            throw new BusinessException(400, "菜单名称不能为空");
        }

        // 验证父菜单是否存在（如果不是顶级菜单）
        if (menu.getParentId() != null && menu.getParentId() != 0) {
            Menu parentMenu = menuService.findById(menu.getParentId());
            if (parentMenu == null) {
                throw new BusinessException(400, "父菜单不存在");
            }
            // 防止循环引用
            if (menu.getParentId().equals(id)) {
                throw new BusinessException(400, "菜单不能设置自身为父菜单");
            }
        }

        menu.setId(id);
        int count = menuService.update(menu);
        if (count <= 0) {
            throw new BusinessException(500, "更新失败");
        }

        // 获取更新后的菜单信息
        Menu updatedMenu = menuService.findById(id);
        return ApiResponse.success(updatedMenu);
    }

    /**
     * 删除菜单
     * 
     * @param id 菜单ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        // 检查菜单是否存在
        Menu menu = menuService.findById(id);
        if (menu == null) {
            throw new NoSuchElementException("菜单不存在");
        }

        // 检查是否有子菜单，如果有则不允许删除
        List<Menu> childMenus = menuService.findByParentId(id);
        if (childMenus != null && !childMenus.isEmpty()) {
            throw new BusinessException(400, "该菜单下有" + childMenus.size() + "个子菜单，不允许删除");
        }

        int count = menuService.delete(id);
        if (count <= 0) {
            throw new BusinessException(500, "删除失败");
        }

        return ApiResponse.success();
    }
}